package com.leetcode.p0;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * 回溯
 */
public class Test93 {

    List<String>  res  = new ArrayList<>();
    Deque<String> path = new ArrayDeque<>(4);
    String        s;

    public List<String> restoreIpAddresses(String s) {
        int len = s.length();
        if (len > 12 || len < 4) {
            return res;
        }
        this.s = s;
        dfs(0, 4);
        return res;
    }

    //剔除一些不变量，最后只保留当前索引和剩余段数
    public void dfs(int begin, int reside) {
        if (begin == s.length()) {
            if (reside == 0) {
                res.add(String.join(".", path));
            }
            return;
        }

        for (int i = begin; i < begin + 3; i++) {
            if (i >= s.length()) {
                break;
            }

            if (s.length() - i > reside * 3) {
                continue;
            }

            if (judgeNumber(s, begin, i)) {
                String curS = s.substring(begin, i + 1);
                path.addLast(curS);
                dfs(i + 1, reside - 1);
                path.removeLast();
            }
        }
    }

    private boolean judgeNumber(String s, int left, int right) {
        int len = right - left + 1;

        if (len > 1 && s.charAt(len) == '0') {
            return false;
        }

        int res = len <= 0 ? len : Integer.parseInt(s.substring(left, right + 1));
        return res >= 0 && res <= 255;
    }

    public static void main(String[] args) {
        Test93 test17 = new Test93();
        System.out.println(test17.restoreIpAddresses("25525511135"));
//        System.out.println(test17.restoreIpAddresses("0000"));
    }

}
